﻿using AutoMapper;
using banyuetan_2_0.Common.Enum;
using banyuetan_2_0.Controllers;
using banyuetan_2_0.IServices;
using banyuetan_2_0.Model;
using banyuetan_2_0.Model.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace banyuetan_2_0.Api.Controllers
{
    /// <summary>
    /// 资源控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [Authorize(Permissions.Name)]
    public class SourceController : BaseApiCpntroller
    {
        readonly ISourceService _sourceService;
        readonly ICategoryService _categoryService;
        private readonly IMapper mapper;
        private readonly IWebHostEnvironment webHostEnvironment;

        public SourceController(ISourceService sourceService, ICategoryService categoryService, IMapper mapper,IWebHostEnvironment webHostEnvironment)
        {
            _sourceService = sourceService;
            _categoryService = categoryService;
            this.mapper = mapper;
            this.webHostEnvironment = webHostEnvironment;
        }

        /// <summary>
        /// 上传文件：默认以categoryid为文件夹进行保存
        /// </summary>
        /// <param name="environment"></param>
        /// <param name="hasMini"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<List<Source>>> Upload([FromServices] IWebHostEnvironment environment,bool hasMini=false) 
        {
            var data = new MessageModel<List<Source>>();
            var sourcelist = new List<Source>();
            var source = new Source();
            string path = string.Empty;
            string foldername = Path.Combine("source",DateTime.Now.Year.ToString()+"-"+DateTime.Now.Month.ToString());//以时间年分作为文件夹进行保存

            IFormFileCollection files = null;


            // 获取提交的文件
            files = Request.Form.Files;
            // 获取附带的数据
            //var max_ver = Request.Form["max_ver"].ObjToString();


            if (files == null || !files.Any()) { data.msg = "请选择上传的文件。"; return data; }
            string folderpath = Path.Combine(environment.WebRootPath, foldername);
            if (!Directory.Exists(folderpath))
            {
                Directory.CreateDirectory(folderpath);
            }
            //格式限制
            var allowPictureType = new string[] { "image/jpg", "image/png", "image/jpeg" };
            var allowMediaType = new string[] { "audio/mp3" };
            var allowVidioType = new string[] { "vidio/mp4"};
            foreach (var item in files)
            {
                switch (item.ContentType)
                {
                    case "image/jpg":
                    case "image/png":
                    case "image/jpeg":
                        {   //foreach (var file in files)
                            if (item.Length <= 1024 * 1024 * 4) //限定上传的文件大小
                            {
                                string filename = DateTime.Now.ToFileTime().ToString();
                                filename = filename + Path.GetExtension(item.FileName);
                                string strpath = Path.Combine(folderpath, filename);
                                //path = Path.Combine(environment.ContentRootPath, strpath);

                                using (var stream = new FileStream(strpath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                                {
                                    await item.CopyToAsync(stream);
                                }
                                
                                source.sHasMini = hasMini;
                                source.sName = filename;
                                source.sType = FileType.Picture;
                                source.sPath = Path.Combine(foldername, filename);
                                source.sUpdateTime = DateTime.Now;
                                await _sourceService.Add(source);
                                //拿到id
                                source = (await _sourceService.Query(s => s.sName == source.sName)).FirstOrDefault();
                                sourcelist.Add(source);
                            }
                            break;
                        }
                    case "Audio":
                        {
                            break;
                        }

                    default:
                        data.msg = "不支持的文件类型!";
                        break;
                };
            }
            if (sourcelist.Count>0)
            {
                data.response = sourcelist;
                data.success = true;
                data.msg = "上传成功";
            }
            return data;
        }

        /// <summary>
        /// 分页获取数据方法
        /// </summary>
        /// <param name="searchDate"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="sType"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<PageModel<Source>> GetPaged([FromQuery] string searchDate, [FromQuery] int pageIndex = 1, [FromQuery] int pageSize = 10,int sType=0)
        {
            var data = new PageModel<Source>();
            var sortString = "sUpdateTime desc";//修改默认排序为以更新时间降序
            //判断是否从前端传回筛选参数，如果有则对应source的Path参数进行比对
            if (sType>2||sType<0)
            {
                return data;
            }
            //Expression<Func<Source, bool>> expression = s => s.sType == (FileType)sType;
            if (string.IsNullOrEmpty(searchDate) || string.IsNullOrWhiteSpace(searchDate))
            {
                searchDate = "";
            }
            if (searchDate != "")
            {
                data = await _sourceService.QueryPage(s => s.sType == (FileType)sType &&  s.sPath.Contains(searchDate), pageIndex, pageSize,sortString);
            }
            else
            {
                data = await _sourceService.QueryPage(s => s.sType == (FileType)sType, pageIndex, pageSize,sortString);
            }
            return data;
        }

        [HttpDelete]
        public async Task<MessageModel<bool>> DeleteSource(int sId)
        {
            var data = new MessageModel<bool>();
            //先找再查
            var target = await _sourceService.QueryById(sId);
            if (target!=null)
            {
                //删除数据库数据
                var delRe = await _sourceService.DeleteById(sId);
                if (delRe)
                {
                    //删除本地文件
                    try
                    {
                        //Directory.GetFileSystemEntries(target.sPath);
                        string rootPath = Path.Combine(webHostEnvironment.WebRootPath, "wwwroot");
                        if (System.IO.File.Exists(Path.Combine(rootPath, target.sPath)))
                        {
                            System.IO.File.Delete(target.sPath);
                        }
                        data.msg = "删除成功！";
                        data.status = 200;
                        data.success = true;
                    }
                    catch (Exception ex)
                    {
                        data.msg = "数据已清除，但文件清除失败！详情见："+ex.Message;
                        return data;
                    }
                }
            }
            else
            {
                data.msg = "未找到指定内容，删除失败！";
            }
            return data;
        }
    }
}
